﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Novapangeia.Dominio;
using Novapangeia.Negocio;
using System.Configuration;
using SharpArch.Data.NHibernate;
using SharpArch.Web.NHibernate;
using System.Text;

namespace Novapangeia.Web
{
    public class Global : System.Web.HttpApplication
    {
        private WebSessionStorage webSessionStorage;
        

        public override void Init()
        {
            //base.Init();
            // The WebSessionStorage must be created during the Init() to tie in HttpApplication events
            webSessionStorage = new WebSessionStorage(this);
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
            //PassarRodada();
            Scheduler.Run("passarRodada", 600, PassarRodada);
            //RegisterRoutes(RouteTable.Routes);
        }

        private static void PassarRodada()
        {
            GerenciadorUsuario GerenciadorUsuario = new GerenciadorUsuario();
            try
            {
                using (UnitOfWork.Start())
                {
                    GerenciadorEstoque.GerarRecursos();
                    GerenciadorUsuario.CalcularScoreUsuarios();
                }
            }
            catch (Exception)
            {
            }
        }

        //private void RegisterRoutes(RouteCollection Routes)
        //{
        //    Route route = new Route("{Parameter}", new HandlerRoteamentoPagina());
        //    Routes.Add(route);
        //}


        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            NHibernateInitializer.Instance().InitializeNHibernateOnce(() => InitializeNHibernateSession());
        }

        /// <summary>
        /// If you need to communicate to multiple databases, you'd add a line to this method to
        /// initialize the other database as well.
        /// </summary>
        private void InitializeNHibernateSession()
        {
            //NHibernateSession.ConfigurationCache = new NHibernateConfigurationFileCache(new string[] { "NovaPangeia.Dominio" });

            NHibernateSession.Init(webSessionStorage,
                new string[] { Server.MapPath("~/bin/NovaPangeia.Mapping.dll") },
                Server.MapPath("~/NHibernate.config"));


        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            // Useful for debugging
            Exception ex = Server.GetLastError();

            if (ex != null)
            {
                if (!ex.Message.Equals("File does not exist."))
                {
                    var logger = log4net.LogManager.GetLogger("LogInFile");

                    StringBuilder errorBuilder = new StringBuilder();
                    errorBuilder.Append("Exception: ");
                    errorBuilder.Append(ex.Message ?? "");
                    errorBuilder.Append(Environment.NewLine);
                    errorBuilder.Append("Stack trace: ");
                    errorBuilder.Append(ex.StackTrace ?? "");
                    if (ex.InnerException != null)
                    {
                        errorBuilder.Append(Environment.NewLine);
                        errorBuilder.Append("Inner Exception: ");
                        errorBuilder.Append(ex.InnerException.Message ?? "");
                        errorBuilder.Append(Environment.NewLine);
                    }

                    logger.Error(errorBuilder.ToString());
                }
            }
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}